package com.security;

import com.entity.UserEntity;
import com.entity.YonghuEntity;
import com.service.UserService;
import com.service.YonghuService;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author t-zhaoheng
 * @since 2022/3/29
 */
@Component
@Slf4j
public class MyUserDetailsService implements UserDetailsService {
  @Resource
  UserService userService;

  @Resource
  YonghuService yonghuService;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // 接受用户传递过来的用户名
//    log.info("认证用户：{}", username);
    // 从数据库中获取用户的信息，包括密码

    YonghuEntity yonghu = yonghuService.getYonghu(username);
    String password = "";
    if(yonghu!=null) {
      password = yonghu.getMima();
    } else {
      UserEntity userEntity = userService.getUser(username);
      password = userEntity.getPassword();
    }

    // 定义权限列表
    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    return new User(username, password, authorities);
  }
}
